<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{fragments/layout :: layout(~{::title}, ~{::section})}">

<head>
    <title>个人信息 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>个人信息</h2>
            <button id="editProfileBtn" class="btn btn-primary">
                <i class="fas fa-edit"></i> 编辑信息
            </button>
        </div>

        <!-- 个人信息卡片 -->
        <div class="row">
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">基本信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="text-center mb-4">
                            <div class="avatar-placeholder mb-3">
                                <i class="fas fa-user fa-5x text-secondary"></i>
                            </div>
                            <h4 id="userName">用户名</h4>
                            <p class="text-muted" id="userRole">普通用户</p>
                        </div>
                        <div id="profileInfo">
                            <div class="mb-3">
                                <label class="font-weight-bold">用户名:</label>
                                <p id="usernameField">loading...</p>
                            </div>
                            <div class="mb-3">
                                <label class="font-weight-bold">姓名:</label>
                                <p id="nameField">loading...</p>
                            </div>
                            <div class="mb-3">
                                <label class="font-weight-bold">性别:</label>
                                <p id="genderField">loading...</p>
                            </div>
                            <div class="mb-3">
                                <label class="font-weight-bold">手机号码:</label>
                                <p id="phoneField">loading...</p>
                            </div>
                            <div class="mb-3">
                                <label class="font-weight-bold">电子邮箱:</label>
                                <p id="emailField">loading...</p>
                            </div>
                            <div class="mb-3">
                                <label class="font-weight-bold">注册时间:</label>
                                <p id="createTimeField">loading...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-8">
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">借阅统计</h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-md-4 mb-3">
                                <div class="border rounded p-3">
                                    <h3 id="totalBorrowCount">0</h3>
                                    <p class="text-muted mb-0">总借阅数</p>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="border rounded p-3">
                                    <h3 id="currentBorrowCount">0</h3>
                                    <p class="text-muted mb-0">当前借阅</p>
                                </div>
                            </div>
                            <div class="col-md-4 mb-3">
                                <div class="border rounded p-3">
                                    <h3 id="overdueCount">0</h3>
                                    <p class="text-muted mb-0">逾期数量</p>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <a href="/user/borrow" class="btn btn-outline-primary btn-block">
                                <i class="fas fa-book-reader"></i> 查看我的借阅记录
                            </a>
                        </div>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">最近评论</h5>
                    </div>
                    <div class="card-body">
                        <div id="commentList">
                            <!-- 评论将通过AJAX加载 -->
                            <div class="text-center">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="sr-only">Loading...</span>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <a href="#" class="btn btn-outline-primary btn-block" id="viewAllCommentsBtn">
                                <i class="fas fa-comments"></i> 查看全部评论
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑个人信息模态框 -->
        <div class="modal fade" id="editProfileModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑个人信息</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editProfileForm">
                            <input type="hidden" id="editId" name="id">
                            <div class="form-group">
                                <label for="editUsername">用户名</label>
                                <input type="text" class="form-control" id="editUsername" name="username" readonly>
                                <small class="form-text text-muted">用户名不可修改</small>
                            </div>
                            <div class="form-group">
                                <label for="editName">姓名</label>
                                <input type="text" class="form-control" id="editName" name="name" required>
                            </div>
                            <div class="form-group">
                                <label>性别</label>
                                <div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="editMale"
                                            value="1">
                                        <label class="form-check-label" for="editMale">男</label>
                                    </div>
                                    <div class="form-check form-check-inline">
                                        <input class="form-check-input" type="radio" name="gender" id="editFemale"
                                            value="2">
                                        <label class="form-check-label" for="editFemale">女</label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="editPhone">手机号码</label>
                                <input type="tel" class="form-control" id="editPhone" name="phone">
                            </div>
                            <div class="form-group">
                                <label for="editEmail">电子邮箱</label>
                                <input type="email" class="form-control" id="editEmail" name="email">
                            </div>
                            <div class="form-group">
                                <label for="editPassword">新密码</label>
                                <input type="password" class="form-control" id="editPassword" name="password">
                                <small class="form-text text-muted">如不修改密码请留空</small>
                            </div>
                            <div class="form-group">
                                <label for="confirmPassword">确认新密码</label>
                                <input type="password" class="form-control" id="confirmPassword" name="confirmPassword">
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveProfileBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <script>
            $(document).ready(function () {
                // 获取当前登录用户信息
                const username = localStorage.getItem('username');
                if (!username) {
                    // 未登录，跳转到登录页面
                    window.location.href = '/login';
                    return;
                }

                // 加载用户信息
                loadUserInfo(username);

                // 加载借阅统计
                loadBorrowStats(username);

                // 加载评论
                loadComments(username);

                // 编辑个人信息按钮点击事件
                $('#editProfileBtn').click(function () {
                    $('#editProfileModal').modal('show');
                });

                // 保存个人信息按钮点击事件
                $('#saveProfileBtn').click(function () {
                    saveUserInfo();
                });

                // 查看全部评论按钮点击事件
                $('#viewAllCommentsBtn').click(function (e) {
                    e.preventDefault();
                    // 这里可以跳转到评论列表页或显示更多评论
                    alert('功能开发中...');
                });
            });

            // 加载用户信息
            function loadUserInfo(username) {
                $.ajax({
                    url: '/user/api/getByUsername/' + username,
                    type: 'GET',
                    success: function (userRes) {
                        if (userRes.code === 200 && userRes.data) {
                            updateUserInfo(userRes.data);
                            fillEditForm(userRes.data);
                        } else {
                            console.error('获取用户信息失败：', userRes.message);
                            alert('获取用户信息失败：' + userRes.message);
                            // window.location.href = '/login'; // 获取失败则跳转到登录页
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，获取用户信息失败:', textStatus, errorThrown, jqXHR);
                        alert('服务器错误，请稍后再试！');
                        // window.location.href = '/login'; // 错误则跳转到登录页
                    }
                });
            }

            // 更新用户信息显示
            function updateUserInfo(user) {
                $('#userName').text(user.name);
                $('#userRole').text(user.role === 0 ? '管理员' : '普通用户');
                $('#usernameField').text(user.username);
                $('#nameField').text(user.name);
                $('#genderField').text(user.gender === 1 ? '男' : (user.gender === 2 ? '女' : '未知'));
                $('#phoneField').text(user.phone || '未设置');
                $('#emailField').text(user.email || '未设置');
                $('#createTimeField').text(moment(user.createTime).format('YYYY-MM-DD HH:mm:ss'));
            }

            // 填充编辑表单
            function fillEditForm(user) {
                $('#editId').val(user.id);
                $('#editUsername').val(user.username);
                $('#editName').val(user.name);
                if (user.gender === 1) {
                    $('#editMale').prop('checked', true);
                } else if (user.gender === 2) {
                    $('#editFemale').prop('checked', true);
                }
                $('#editPhone').val(user.phone);
                $('#editEmail').val(user.email);
                // 密码不回显
                $('#editPassword').val('');
                $('#confirmPassword').val('');
            }

            // 保存用户信息
            function saveUserInfo() {
                // 获取表单数据
                const id = $('#editId').val();
                const username = $('#editUsername').val();
                const name = $('#editName').val();
                const gender = $('input[name="gender"]:checked').val();
                const phone = $('#editPhone').val();
                const email = $('#editEmail').val();
                const password = $('#editPassword').val();
                const confirmPassword = $('#confirmPassword').val();

                // 表单验证
                if (!name) {
                    alert('请输入姓名');
                    return;
                }

                if (password && password !== confirmPassword) {
                    alert('两次输入的密码不一致');
                    return;
                }

                // 构建用户数据
                const userData = {
                    id: id,
                    username: username,
                    name: name,
                    gender: gender,
                    phone: phone,
                    email: email
                };

                if (password) {
                    userData.password = password;
                }

                // 实际项目中应该发送AJAX请求到后端保存数据
                $.ajax({
                    url: '/user/api/update',
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(userData),
                    success: function(res) {
                        if (res.code === 200) {
                            alert('保存成功！');
                            $('#editProfileModal').modal('hide');
                            // 重新加载用户信息
                            loadUserInfo(username);
                        } else {
                            console.error('保存失败：', res.message);
                            alert('保存失败：' + res.message);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，保存用户信息失败:', textStatus, errorThrown, jqXHR);
                        alert('服务器错误，请稍后再试！');
                    }
                });
            }

            // 加载借阅统计
            function loadBorrowStats(username) {
                // 需要先获取用户ID，假设可以通过用户名获取
                $.ajax({
                    url: '/user/api/getByUsername/' + username,
                    type: 'GET',
                    success: function (userRes) {
                        if (userRes.code === 200 && userRes.data) {
                            const userId = userRes.data.id;
                            $.ajax({
                                url: '/borrow/api/statistics/' + userId,
                                type: 'GET',
                                success: function (statsRes) {
                                    if (statsRes.code === 200 && statsRes.data) {
                                        $('#totalBorrowCount').text(statsRes.data.totalBorrowCount);
                                        $('#currentBorrowCount').text(statsRes.data.currentBorrowCount);
                                        $('#overdueCount').text(statsRes.data.overdueCount);
                                    } else {
                                        console.error('获取借阅统计失败：', statsRes.message);
                                        alert('获取借阅统计失败：' + statsRes.message);
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.error('服务器错误，获取借阅统计失败:', textStatus, errorThrown, jqXHR);
                                    alert('服务器错误，请稍后再试！');
                                }
                            });
                        } else {
                            console.error('获取用户ID失败：', userRes.message);
                            alert('获取用户ID失败：' + userRes.message);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，获取用户ID失败:', textStatus, errorThrown, jqXHR);
                        alert('服务器错误，请稍后再试！');
                    }
                });
            }

            // 加载评论
            function loadComments(username) {
                // 需要先获取用户ID
                $.ajax({
                    url: '/user/api/getByUsername/' + username,
                    type: 'GET',
                    success: function (userRes) {
                        if (userRes.code === 200 && userRes.data) {
                            const userId = userRes.data.id;
                            $.ajax({
                                url: '/comment/api/listByUserId/' + userId,
                                type: 'GET',
                                success: function (commentRes) {
                                    if (commentRes.code === 200 && commentRes.data) {
                                        renderComments(commentRes.data);
                                    } else {
                                        console.error('获取评论失败：', commentRes.message);
                                        alert('获取评论失败：' + commentRes.message);
                                    }
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    console.error('服务器错误，获取评论失败:', textStatus, errorThrown, jqXHR);
                                    alert('服务器错误，请稍后再试！');
                                }
                            });
                        } else {
                            console.error('获取用户ID失败：', userRes.message);
                            alert('获取用户ID失败：' + userRes.message);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.error('服务器错误，获取评论的用户ID失败:', textStatus, errorThrown, jqXHR);
                        alert('服务器错误，请稍后再试！');
                    }
                });
            }

            // 渲染评论列表
            function renderComments(comments) {
                let html = '';

                if (comments && comments.length > 0) {
                    // 只显示最新的两条评论
                    const displayComments = comments.slice(0, 2);
                    for (let i = 0; i < displayComments.length; i++) {
                        const comment = displayComments[i];
                        const stars = '★'.repeat(comment.rating) + '☆'.repeat(5 - comment.rating);
                        const createTime = moment(comment.createTime).format('YYYY-MM-DD HH:mm:ss');

                        html += `
                            <div class="media mb-3">
                                <div class="media-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="mt-0">${comment.bookName}</h5>
                                        <span class="text-warning">${stars}</span>
                                    </div>
                                    <p>${comment.content}</p>
                                    <small class="text-muted">${createTime}</small>
                                </div>
                            </div>
                        `;

                        if (i < displayComments.length - 1) {
                            html += '<hr>';
                        }
                    }
                } else {
                    html = '<p class="text-center text-muted">暂无评论</p>';
                }

                $('#commentList').html(html);
            }
        </script>
    </section>
</body>

</html>